package com.ruoyi.system.service.impl;

import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.SysOutlog;
import com.ruoyi.system.service.SysOutputLogService;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLDecoder;
import java.text.DecimalFormat;
import java.util.*;

@Service
public class SysOutputLogServiceImpl implements SysOutputLogService {

	@Override
	public List<SysOutlog> getsyslog(String syslogpath, SysOutlog syslog, String isAsc) throws UnsupportedEncodingException {
		List<SysOutlog> json = new ArrayList<SysOutlog>();
		// 判断当前文件夹是否是一个文件夹
		if(syslog.getPath()!=null&&syslog.getPath().length()>0) {
			syslogpath= URLDecoder.decode(URLDecoder.decode(syslog.getPath(), "utf-8"), "utf-8");
		}
		
		try {
			json = getFile(syslogpath,0,0);
		} catch (Exception e) {
			e.printStackTrace();
		}
		//时间排序 根据当前传递的数据进行排序
		if(json.size()<=0) {
			return json;
		}
		//升序
		if(StringUtils.isNotBlank(isAsc)&&isAsc.equals("asc")) {
			upsort(json);
		}else {
			downsort(json);
		}
		//开始讲将当前的文件夹进行里面对象为0的取到
		List<SysOutlog> packlist= new ArrayList<SysOutlog>();
		for (int i = 0; i < json.size(); i++) {
			
			if(json.get(i).getParintid()==0&&json.get(i).isIfpack()) {
				SysOutlog sysOutlog = json.get(i);
				json.remove(i);
				json.add(0, sysOutlog);
			}
		}
		
		return json;
	}

	private void downsort(List<SysOutlog> json) {
		Collections.sort(json, new Comparator<SysOutlog>() {
			@Override
			public int compare(SysOutlog o1, SysOutlog o2) {
				try {
					if(o1.getTime() == null || o2.getTime() == null){
						return 1;
					}
					Date dt1 = o1.getTime();
					Date dt2 = o2.getTime();

					if (dt1.getTime() > dt2.getTime()) {
						return -1;
					} else if (dt1.getTime() < dt2.getTime()) {
						return 1;
					} else {
						return 0;
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
				return 0;
			}
		});
		
	}

	private void upsort(List<SysOutlog> json) {
		Collections.sort(json, new Comparator<SysOutlog>() {
			@Override
			public int compare(SysOutlog o1, SysOutlog o2) {
				try {
					if(o1.getTime() == null || o2.getTime() == null){
						return 1;
					}
					Date dt1 = o1.getTime();
					Date dt2 = o2.getTime();

					if (dt1.getTime() > dt2.getTime()) {
						return 1;
					} else if (dt1.getTime() < dt2.getTime()) {
						return -1;
					} else {
						return 0;
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
				return 0;
			}
		});
		
	}
	int jq=0;
	private List<SysOutlog> getFile(String packfile, int syslogpath, int j) throws Exception {
		List<SysOutlog> json = new ArrayList<SysOutlog>();
		
		File file = new File(packfile);
		boolean exists = file.exists();
		if (!exists) {
			return json;
		}
		File[] array = file.listFiles();
		if (array.length <= 0) {
			return json;
		}
		
		for (int i = 0; i < array.length; i++) {
			SysOutlog filenamemap = new SysOutlog();
			 jq++;
			filenamemap.setId(jq);
			String name = array[i].getName();
			String filepath = array[i].getPath();
			long length = array[i].length();
			File newfile = new File(array[i].getPath());
			Calendar cal = Calendar.getInstance();
			long time = newfile.lastModified();
			cal.setTimeInMillis(time);
			filenamemap.setName(name);
			filenamemap.setPath(filepath);
			filenamemap.setTime(cal.getTime());
			if (array[i].isFile()) {
				filenamemap.setFilesize(getFileSize(length));
				filenamemap.setIfpack(false);
				filenamemap.setParintid(j);
				json.add(filenamemap);
			} else if (array[i].isDirectory()) {
				filenamemap.setIfpack(true);
				filenamemap.setParintid(syslogpath);
				json.add(filenamemap);
				List<SysOutlog> digui = getFile(array[i].getPath(),jq,jq);
			}
		}

		return json;

	}

	@Override
	public void down(HttpServletResponse response, String pathstr) throws FileNotFoundException {
		// 获取服务器文件
		File file = new File(pathstr);
		InputStream ins = new FileInputStream(file);
		/* 设置文件ContentType类型，这样设置，会自动判断下载文件类型 */
		response.setContentType("multipart/form-data");
		/* 设置文件头：最后一个参数是设置下载文件名 */
		response.setHeader("Content-Disposition", "attachment;filename=" + file.getName());
		try {
			OutputStream os = response.getOutputStream();
			byte[] b = new byte[1024];
			int len;
			while ((len = ins.read(b)) > 0) {
				os.write(b, 0, len);
			}
			os.flush();
			os.close();
			ins.close();
		} catch (IOException ioe) {
			ioe.printStackTrace();
		}

	}

	/**
	 * 获取文件的大小
	 * 
	 * @title: getFileSize
	 * @description:TODO
	 * @author: dlq1751087535@163.com
	 * @param size
	 * @return
	 * @date：2020年5月11日上午10:30:11
	 */
	public static String getFileSize(long size) {
		double cache = size / 1024f;
		String unit = "K";
		if (cache >= 1024f) {
			cache /= 1024f;
			unit = "M";
		}
		if (cache >= 1024f) {
			cache /= 1024f;
			unit = "G";
		}
		if (cache >= 1024f) {
			cache /= 1024f;
			unit = "T";
		}
		return new DecimalFormat("0.00").format(cache) + unit;
	}
}
